import { PageList } from "@mallfoundry/shared/data"
import { Role, RoleService } from "@mallfoundry/store/role"
import { useEffect, useState } from "react"

export function useRole(storeId: string, roleId: string) {
  const [loading, setLoading] = useState<boolean>(false)
  const [role, setRole] = useState(new Role())

  useEffect(refresh, [storeId, roleId])

  function refresh() {
    setLoading(true)
    RoleService.getRole({
      storeId,
      id: roleId,
    })
      .then(setRole)
      .finally(() => setLoading(false))
  }

  return {
    loading,
    setRole,
    refresh,
    role,
  }
}


interface UseRolesOptions {
  storeId?: string
}

export function useRoles(options: UseRolesOptions) {
  const { storeId } = options
  const [loading, setLoading] = useState<boolean>(false)
  const [pageRoles, setPageRoles] = useState(new PageList<Role>())

  useEffect(refresh, [storeId])

  function refresh() {
    setLoading(true)
    RoleService.getRoles(
      RoleService.createRoleQuery()
        .toBuilder()
        .storeId(storeId)
        .build())
      .then(setPageRoles)
      .finally(() => setLoading(false))
  }

  return {
    loading,
    refresh,
    ...pageRoles,
  }
}
